<template>
  <Nuxt-Layout>
    <div class="con">
      <div class="con-cen">
        <div class="con-cen-video">
          <h2 class="con-cen-video-title">{{ currentVideo.title || '请选择课程章节下的视频' }}</h2>
          <div class="con-cen-video-left">
            <p class="con-cen-video-left-notice">请选择课程章节下的视频</p>
          </div>
          <div class="con-cen-video-right">
            <p class="con-cen-video-right-title">目录（{{ chapterData.length }}）</p>
            <div style="height: 20px;"></div>
            <el-scrollbar height="370">
              <el-collapse v-model="chapterIndex" accordion>
                <el-collapse-item v-for="(item, index) in chapterData" :key="item.id"
                  :title="`${(index + 1) < 10 ? '0' + (index + 1) : (index + 1)} ${item.name}`" :name="index"
                  @change="chapterIndex = index">
                  <a class="el-button el-button--large is-text videos-btn" v-for="ite in item.videos"
                    :key="ite.id" :href="ite.href" :title="ite.title" :class="ite.id == currentVideo.id ? 'el-button--primary' : ''">
                    <el-icon style="margin-right: 5px;">
                      <VideoCamera />
                    </el-icon>
                    <p class="videos-btn-text">{{ ite.title }}</p>
                    <el-text type="info" v-if="ite.progress">{{ ite.progress.status == 1 ? '学习中' : ite.progress.status
                      == 2 ? '已学完' : '未学习' }}</el-text>
                    <el-text type="info" v-else>未学习</el-text>
                  </a>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </div>
        </div>
        <div class="con-cen-info">
          <p class="con-cen-info-title">{{ infoData.title }}</p>
          <ul class="con-cen-info-desc">
            <li class="con-cen-info-desc-li">
              <strong>今日已获学时：</strong>{{ infoData.userDayOfHours || 0 }}
            </li>
            <li class="con-cen-info-desc-li">
              <strong>视频学时：</strong>{{ currentVideo.hours || 0 }}
            </li>
            <li class="con-cen-info-desc-li">
              <strong>课程讲师：</strong>{{ infoData.teachers && infoData.teachers.length > 0 ? infoData.teacher.map(x => x.name).join('，') : "-" }}
            </li>
          </ul>
          <div class="con-cen-info-notice" v-if="isLogin && !infoData.purchased">
            <el-icon class="notice-icon">
              <WarningFilled />
            </el-icon>
            <p class="notice-text">
              <span>提醒：所有课程可免费观看30秒，继续观看请</span>
              <el-text type="danger" style="cursor: pointer;" @click="buyCourseFn">点击购买</el-text>
            </p>
          </div>
        </div>
      </div>
    </div>
  </Nuxt-Layout>
</template>

<script setup>
import { VideoCamera, WarningFilled } from '@element-plus/icons-vue'
import { getLessonInfoApi, getCommentApi, addCommentApi, replyCommentApi, lessonPurchaseApi } from '~/server/api';
import { isEmpty } from "~/utils/utils";
import { useCountStore } from "~/store/counter.js";
useCountStore().$patch({ indexActive: 3 });
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
const seoTitle = ref("技考邦_课程详情");
const seoKeywords = ref("技考邦,课程详情");
const seoDescription = ref("技考邦，课程详情。");
const isLogin = ref(!isEmpty(useRoute().meta.userinfo) ? true : false);
const courseId = useRoute().params.courseId || '';
const chapterId = useRoute().params.chapterId || '';
// 验证路由
definePageMeta({
  validate: async (route) => {
    return false;
  }
})
// 获取详情
const infoData = ref({});
const chapterData = ref([]);
const chapterIndex = ref(0);
const currentVideo = ref({});
const getInfo = async () => {
  let { data: infoRes } = await useAsyncData("getLessonInfoApi", () =>
    useServerRequest(getLessonInfoApi, {
      method: "get",
      params: {
        courseId: courseId
      },
    })
  );
  if (infoRes.value && infoRes.value.errno === 0 && infoRes.value.result) {
    infoData.value = infoRes.value.result;
    // 修改TDK
    seoTitle.value = infoData.value.title;
    seoDescription.value = infoData.value.brief;
    // 章节 默认跳转第一章节
    if (infoData.value.chapters && infoData.value.chapters.length > 0) {
      let chaptersFlag = true;
      infoData.value.chapters.forEach((item, index) => {
        if (item.id == chapterId) {
          chapterIndex.value = index;
          chaptersFlag = false;
          // 修改TDK
          seoTitle.value = item.name;
          seoKeywords.value = `技考邦,${infoData.value.title},${item.name}`;
          seoDescription.value = `${infoData.value.brief}，${item.name}`;
        }
        // 设置视频跳转路径
        if (item.videos && item.videos.length > 0) {
          item.videos.forEach(ite => {
            ite.href = `/curriculum_details/${infoData.value.id}-${item.id}-${ite.id}.html`
          })
        }
      })
      // 判断章节是否存在
      if (chapterId && chaptersFlag || courseId && !chapterId && videoId) {
        showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` })
      }
      chapterData.value = infoData.value.chapters;
    }
    return false;
  }
  showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` });
};
getInfo();
// 购买课程
const buyCourseDisabled = ref(false)
const buyCourseFn = async () => {
  buyCourseDisabled.value = true;
  let { errno, errmsg, result } = await useServerRequest(lessonPurchaseApi, {
    method: 'post',
    body: JSON.stringify({
      id: infoData.value.id
    })
  })
  if (errno === 0 && !result) {
    ElMessage({
      message: '购买成功',
      type: 'success'
    })
    infoData.value.purchased = true;
    buyCourseDisabled.value = false;
    return false;
  }
  if (errno === 0 && result) {
    window.location.href = `/trading/${courseId}.html`;
  }
  buyCourseDisabled.value = false;
}
// seo
useSeoMeta({
  title: seoTitle,
  keywords: seoKeywords,
  description: seoDescription,
  ogTitle: seoTitle,
  ogDescription: seoDescription,
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
</script>

<style lang="less">
.info-top-right-star {
  .el-rate .el-rate__icon {
    margin-right: 2px;
  }

  .el-rate__text {
    margin-left: 5px;
  }
}

.con-cen-video-right {
  .el-collapse-item__header.is-active {
    color: #409EFF;
  }
}
</style>
<style lang="less" scoped>
.con {
  padding: 20px 0;
  min-height: calc(100vh - 454px);

  &-cen {
    width: 1200px;
    margin: 0 auto;

    &-video {
      background: #FFFFFF;
      border-radius: 10px;
      border: 1px solid #EAEAE6;
      padding: 20px;
      display: flex;
      flex-wrap: wrap;
      align-items: stretch;

      &-title {
        flex: 100%;
        font-weight: bold;
        font-size: 18px;
        margin: 0 0 20px 0;
      }

      &-left {
        width: 730px;
        height: 410px;
        line-height: 410px;
        text-align: center;
        margin-right: 20px;
        background-color: #000;
        overflow: hidden;
        position: relative;

        &-notice {
          color: #fff;
        }
      }

      &-right {
        flex: 1;
        overflow: hidden;

        &-title {
          font-weight: bold;
          font-size: 18px;
          height: 20px;
          line-height: 20px;
        }

        .el-button+.el-button {
          margin-left: 0;
        }

        .videos-btn {
          width: 100%;
          justify-content: flex-start;

          &-text {
            text-align: left;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 30%;
          }
        }
      }
    }

    &-info {
      margin-top: 20px;
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #eaeae6;
      padding: 20px;

      &-title {
        font-weight: bold;
        font-size: 18px;
      }

      &-desc {
        margin-top: 20px;
        display: flex;
        align-items: flex-start;

        &-li {
          margin-right: 20px;
          font-size: 16px;
          color: #666666;

          strong {
            color: #666666;
            font-size: 16px;
          }
        }
      }

      &-notice {
        height: 50px;
        background: #FFEDED;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding: 0 16px;
        margin-top: 10px;

        .notice-icon {
          color: #FF0000;
          margin-right: 16px;
          font-size: 17px;
        }

        .notice-text {
          font-size: 14px;
        }
      }
    }
  }
}

.left-details {
  padding: 20px;
  background: #ffffff;
  border-radius: 10px;
  border: 1px solid #eaeae6;

  &-title {
    font-weight: bold;
    font-size: 18px;
    color: #666666;
  }

  &-con {
    margin-top: 20px;

    img {
      max-width: 100%;
    }
  }

  &-message {
    &-li {
      border-bottom: 1px solid #eaeae6;
      padding: 20px 0;

      &-name {
        font-size: 15px;
        display: flex;
        align-items: center;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      &-con {
        margin-top: 5px;
        font-size: 14px;
        color: #666;
        display: flex;
        align-items: flex-start;
      }

      &:last-child {
        border-bottom: 0;
        padding-bottom: 0;
      }
    }
  }

  &-release {
    margin-top: 20px;

  }
}

.pagin {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

p {
  margin: 0;
}
</style>
